package org.template.dao;

import java.util.List;

import org.springframework.stereotype.Repository;
import org.template.dao.iter.RedisDelegator;

import redis.clients.jedis.Jedis;

@Repository
public class ListRedisDao extends BaseRedisDao {

	public List<String> getElement(final String key, final int start, final int end) {

		return run(new RedisDelegator<List<String>>() {
			@Override
			public List<String> execute(Jedis redis) {
				return redis.lrange(key, start, end);
			}
		});

	}

	public long getSize(final String listKey) {

		return run(new RedisDelegator<Long>() {
			@Override
			public Long execute(Jedis redis) {
				return redis.llen(listKey);
			}
		});

	}

	public long addTailElement(String listKey, String... value) {
		return addListElement(listKey, true, value);
	}

	public long addHeadElement(String listKey, String... value) {
		return addListElement(listKey, false, value);
	}

	public String removeTailElement(String listKey) {
		return getListElement(listKey, true);
	}

	public String removeHeadElement(String listKey) {
		return getListElement(listKey, false);
	}

	protected long addListElement(final String listKey, final boolean isTail, final String... value) {

		return run(new RedisDelegator<Long>() {
			@Override
			public Long execute(Jedis redis) {
				if (isTail)
					return redis.rpush(listKey, value);
				return redis.lpush(listKey, value);
			}
		});

	}

	protected String getListElement(final String listKey, final boolean isTail) {

		return run(new RedisDelegator<String>() {
			@Override
			public String execute(Jedis redis) {
				if (isTail)
					return redis.rpop(listKey);
				return redis.lpop(listKey);
			}
		});

	}

}
